/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.dat076.datesite.controllers;

import edu.chl.dat076.datesite.ejbs.UserEJBLocal;
import edu.chl.dat076.datesite.entities.SiteUser;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

/**
 *
 * @author Mikey
 */

@ManagedBean
@ViewScoped
public class ProfileSettingsBackingBean implements Serializable {
  
    @EJB
    private UserEJBLocal userJPACtrl;

    private SiteUser user;
    private String passwordOne;
    private String passwordTwo;
    
    @PostConstruct
    public void postConstruct () {
        user = userJPACtrl.getUser(FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user").toString());
    }

    public SiteUser getUser () {
        return user;
    }

    public String getPasswordOne() {
        return passwordOne;
    }

    public void setPasswordOne(String passwordOne) {
        this.passwordOne = passwordOne;
    }

    public String getPasswordTwo() {
        return passwordTwo;
    }

    public void setPasswordTwo(String passwordTwo) {
        this.passwordTwo = passwordTwo;
    }
    
    public String deleteProfile() {
        userJPACtrl.deleteUser(user.getUsername());
        return "deleteProfile";
    }
    
    public String saveProfile() {
        String message="";
        Severity severity;
        try {
            // password fields do not match, no profile update
            if (!passwordOne.equals(passwordTwo)) {
                message = ("Password fields do not match.");
                severity = FacesMessage.SEVERITY_ERROR;
            }
            
            // password fields match
            // if not empty, the password is updated,
            // otherwise just the email
            else {
                if (!passwordOne.equals("")) user.setPassword(passwordOne);
                userJPACtrl.editUser(user);
                message=("Your profile has been updated."); 
                severity = FacesMessage.SEVERITY_INFO;
            }
        }
        catch (Exception e) {
            message=("Failed to update your profile.");
            severity = FacesMessage.SEVERITY_ERROR;
        }
        FacesContext.getCurrentInstance().addMessage("Profile", new FacesMessage(severity, message, message));
        return "updateProfile";
    }
}
